package com.enhe.gck.fg;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.CarbonEnumKeyValue;
import com.enhe.gck.CarbonRelationType;
import com.enhe.gck.communal.*;
import com.enhe.gck.domain.PrintInvoiceSet;
import com.enhe.gck.item.DeductionHWANE16713Item;
import com.enhe.gck.item.FileHWANE18503Item;
import com.enhe.gck.item.InvoicingHWANE18525Item;
import com.enhe.gck.item.OrderHWANE16677Item;
import com.enhe.gck.pojo.*;
import com.enhe.gck.service.impl.InvoiceExportSetService;
import com.kuangkie.carbon.fg.FuncGroupContext;
import com.kuangkie.carbon.fg.ImproveResultFactory;
import com.kuangkie.carbon.fg.SecondRoundImproveFuncGroup;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.FGRecord;
import com.kuangkie.carbon.record.FGRecordComplexus;
import com.kuangkie.carbon.record.ProRecord;
import com.kuangkie.carbon.record.RecordQueryProConJunctionFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@Repository(value = "hwane18525366042330866425862")
public class InvoicingHWANE18525BNB implements SecondRoundImproveFuncGroup {

    @Resource
    private FileTemplateHWANE18473BNB fileTemplateHWANE18473BNB;

    @Resource
    private InvoiceExportSetService invoiceExportSetService;
    @Resource
    private ConfigHWANE16627BNB configHWANE16627BNB;


    @Override
    public void secondImprove(FuncGroupContext context, ProRecord proRecord, FGRecordComplexus recordComplexus,
                              ImproveResultFactory improveResultFactory) {
        Invoicing info = proRecord.getBean(Invoicing.class);
        log.info("发票新增/修改业务开始:{}", JSONUtil.toJsonStr(info));

        String goodId = null;

        if (proRecord.isNew()) {
            OperationLogHWANE21797BNB.save(improveResultFactory, 3, 1, proRecord.getRecordCode());
            log.info("验证客户");
            boolean isRetail = false;
            String customerId = proRecord.getGuestRecordCode(CarbonRelationType.RR_开票记录_客户_客户管理);
            Customer customer;
            if (StringUtils.isEmpty(customerId)) {
                log.info("客户为空");
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_1);
                return;
            } else {
                customer = CarbonPanel.getRecordDiscover(CarbonBaseConstant.客户管理_khgl).getRecordBean(customerId, Customer.class, 2);
                if (String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_散户_sh).equals(customer.getType())) {
                    isRetail = true;
                }
            }
            log.info("客户是否散户：{}", isRetail);
            Collection<String> orderIds = proRecord.getGuestRecordCodes(CarbonRelationType.RR_开票记录_订单记录_订单记录);
            boolean isCash = false;
            boolean isCredit = false;
            if (!CollectionUtils.isEmpty(orderIds)) {
                log.info("验证订单条数");
                int count = 0;
                for (String orderId : orderIds) {
                    // 查询扣款记录
                    RecordQueryProConJunctionFactory rqpcjf = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.扣款记录_kkjl).getProConJunctionFactory()
                            .addEqual(DeductionHWANE16713Item.基本属性组_是否散户扣款, isRetail);
                    rqpcjf.getRelationCriterionFactory(CarbonBaseConstant.订单记录_ddjl)
                            .setInRelationTypes(CarbonRelationType.RR_扣款记录_订单名称_订单记录)
                            .setInGuestCodes(orderId);

                    List<Deduction> deductionList = rqpcjf.goBack().queryBeans(Deduction.class, 3);
                    if (deductionList != null) {
                        count = count + deductionList.size();
                        for (Deduction deduction : deductionList) {
                            if (deduction.getRecharge() != null) {
                                if (String.valueOf(CarbonEnumKeyValue.充值记录_充值类型_授信_sx).equals(deduction.getRecharge().getType())) {
                                    // 授信直接使用银行转账
                                    if (!isCredit) {
                                        isCredit = true;
                                    }
                                } else {
                                    if (deduction.getRecharge().getBank() != null) {
                                        // 判断银行账户是否是现金账户
                                        if (Boolean.FALSE.equals(deduction.getRecharge().getBank().getIsCash())) {
                                            if (!isCredit) {
                                                isCredit = true;
                                            }
                                        } else {
                                            if (!isCash) {
                                                isCash = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
//				if(count<1||count>15){
//					log.info("不能为空且在1~15条内。");
//					PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_8);
//					return;
//				}

                //新增 同产品验证
                List<ProRecord> orderRecordList = new ArrayList<>(recordComplexus.getGuestProRecords(proRecord.getModelCode(), proRecord.getRecordCode(), CarbonRelationType.RR_开票记录_订单记录_订单记录));
                if (!CollectionUtils.isEmpty(orderRecordList)) {
                    for (ProRecord record : orderRecordList) {
                        if (goodId == null) {
                            goodId = record.getGuestRecordCode(CarbonRelationType.RR_订单记录_产品物料_产品管理);
                        } else {
                            if (!goodId.equals(record.getGuestRecordCode(CarbonRelationType.RR_订单记录_产品物料_产品管理))) {
                                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_12);
                                return;
                            }
                        }
                    }
                }
            } else {
                log.info("请选择订单");
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_2);
                return;
            }

            log.info("验证订单的下单客户信息");
            List<ProRecord> list = new ArrayList<>(recordComplexus.getGuestProRecords(proRecord.getModelCode(), proRecord.getRecordCode(), CarbonRelationType.RR_开票记录_订单记录_订单记录));
            if (!CollectionUtils.isEmpty(list)) {
                if (isRetail) {
                    log.info("验证是否对应散户");
                    for (ProRecord record : list) {
                        if (!String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(record.getString(OrderHWANE16677Item.基本属性组_是否散户下单))) {
                            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_32);
                            return;
                        }
                        if (!customerId.equals(record.getGuestRecordCode(CarbonRelationType.RR_订单记录_散户_客户管理))) {
                            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_3);
                            return;
                        } else {
                            if (Boolean.TRUE.equals(record.getBoolean(OrderHWANE16677Item.基本属性组_是否已开票))) {
                                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_6);
                                return;
                            }
                        }
                    }
                } else {
                    log.info("验证是否对应经销商");
                    for (ProRecord record : list) {
                        boolean isR = String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(record.getString(OrderHWANE16677Item.基本属性组_是否散户下单));
                        if (isR) {
                            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_31);
                            return;
                        }
                        if (!customerId.equals(record.getGuestRecordCode(CarbonRelationType.RR_订单记录_客户名称_客户管理))) {
                            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_3);
                            return;
                        } else {
                            boolean isOk = Boolean.TRUE.equals(record.getBoolean(OrderHWANE16677Item.基本属性组_是否已开票));
                            if (isOk) {
                                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_6);
                                return;
                            }
                        }
                    }
                }

                InvoiceHeader invoiceHeader = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.发票抬头_fptt).queryABean(InvoiceHeader.class);
                if (invoiceHeader == null) {
                    PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_4);
                    return;
                }
                FGRecord inputStreamF = fileTemplateHWANE18473BNB.getInfo(CarbonEnumKeyValue.文件模板_发票模板_fpmb);
                if (inputStreamF == null) {
                    PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_5);
                    return;
                }

                log.info("验证关联客户是否有开票信息");
                if (customer.getInvoiceInfo() == null) {
                    PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_7);
                    return;
                }

                saveInvoicingNew(proRecord, customer, customer.getInvoiceInfo(), improveResultFactory, list, invoiceHeader,
                        fileTemplateHWANE18473BNB.getInfoFile(inputStreamF), isRetail, isCash, isCredit, goodId, info);
            } else {
                log.info("查数据为空，异常");
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_2);
                return;
            }
        }

        if (String.valueOf(CarbonEnumKeyValue.操作命令_发票重写_fpzx).equals(info.getCommand())) {
            OperationLogHWANE21797BNB.save(improveResultFactory, 3, 2, proRecord.getRecordCode());
            log.info("验证客户");
            String customerId = proRecord.getGuestRecordCode(CarbonRelationType.RR_开票记录_客户_客户管理);
            Customer customer;
            if (StringUtils.isEmpty(customerId)) {
                log.info("客户为空");
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_1);
                return;
            } else {
                customer = CarbonPanel.getRecordDiscover(CarbonBaseConstant.客户管理_khgl).getRecordBean(customerId, Customer.class, 2);
            }
            InvoiceHeader invoiceHeader = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.发票抬头_fptt).queryABean(InvoiceHeader.class);
            if (invoiceHeader == null) {
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_4);
                return;
            }
            FGRecord inputStreamF = fileTemplateHWANE18473BNB.getInfo(CarbonEnumKeyValue.文件模板_发票模板_fpmb);
            if (inputStreamF == null) {
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_5);
                return;
            }
            log.info("验证关联客户是否有开票信息");
            if (customer.getInvoiceInfo() == null) {
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_7);
                return;
            }

            try {
                String[] quantity = info.getQuantity().split(";");
                String[] amount = info.getAmount().split(";");
                String[] unit = info.getUnit().split(";");
                if (!(quantity.length == amount.length)) {
                    PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_13);
                    return;
                }
            } catch (Exception e) {
                PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_13);
                return;
            }

            saveInvoicingNewInput(proRecord, info, customer, customer.getInvoiceInfo(), improveResultFactory, invoiceHeader, fileTemplateHWANE18473BNB.getInfoFile(inputStreamF));
        }

        isCancel(info, proRecord, improveResultFactory);
    }

    /**
     * 作废
     */
    private void isCancel(Invoicing info, ProRecord proRecord, ImproveResultFactory improveResultFactory) {
        if (info.getIsCancel() != null && info.getIsCancel()) {
            Invoicing infoOld = PublicMethod.getInfo(CarbonBaseConstant.开票记录_kpjl, proRecord.getRecordCode(), Invoicing.class);
            if (!(infoOld != null && infoOld.getIsCancel())) {
                OperationLogHWANE21797BNB.save(improveResultFactory, 3, 3, proRecord.getRecordCode());
                Collection<String> listOrId = proRecord.getGuestRecordCodes(CarbonRelationType.RR_开票记录_订单记录_订单记录);
                if (listOrId != null) {
                    for (String s : listOrId) {
                        PublicMethod.updateAny(improveResultFactory, CarbonBaseConstant.订单记录_ddjl, s).putAttribute(OrderHWANE16677Item.基本属性组_是否已开票, false);
                    }
                }
            }
        }

    }

    private void saveInvoicingNew(ProRecord proRecord, Customer customer, InvoiceInfo invoiceInfo, ImproveResultFactory improveResultFactory,
                                  List<ProRecord> list, InvoiceHeader invoiceHeader, byte[] inputStream, boolean isRetail, boolean isCash, boolean isCredit, String goodId, Invoicing info) {
        log.info("开始生成发票,{}", proRecord.toJson());
        PrintInvoiceSet printInvoice = new PrintInvoiceSet();
        printInvoice.setClientName(customer.getName());

        printInvoice.setGckVATNO(invoiceHeader.getData1());
        printInvoice.setGckNIF(invoiceHeader.getData2());
        printInvoice.setGckIDN(invoiceHeader.getData3());
        printInvoice.setSalesSlip(invoiceHeader.getCompiled());//销售发票参考编成

        printInvoice.setInvoiceNo(PublicMethod.getOrderCodeFV());//发票号
        printInvoice.setClientVATNO(invoiceInfo.getData1());
        printInvoice.setClientVAT(invoiceInfo.getVat());
        printInvoice.setClientNIF(invoiceInfo.getData2());
        printInvoice.setClientIDN(invoiceInfo.getData3());
        printInvoice.setAddress(invoiceInfo.getCountry());//地址信息
//		printInvoice.setRoadNumber(invoiceInfo.getAddress2());//路号地址
//		printInvoice.setProvince(invoiceInfo.getProvinces());//省
//		printInvoice.setState(invoiceInfo.getCountry());//国家
        printInvoice.setRemark(invoiceInfo.getProvinces());

        printInvoice.setCash(isCash);
        printInvoice.setCredit(isCredit);

        BigDecimal totalAmountEXVAT = BigDecimal.ZERO;
        BigDecimal avtAmount = BigDecimal.ZERO;
        BigDecimal amountUSD = BigDecimal.ZERO;
        BigDecimal amountCDF = BigDecimal.ZERO;

        BigDecimal sumWeight = BigDecimal.ZERO;
        List<PrintInvoiceSet.InvoiceItemsSet> items = new ArrayList<>();

        // 单价map，key：产品单价，value：<number：购买量，money：扣款金额>
        Map<BigDecimal, PublicEntity.NumberMoney> unitPriceMap = new LinkedHashMap<>();
        // 订单扣款最大税率
        BigDecimal rate = BigDecimal.ZERO;
        for (ProRecord record : list) {
            Order order = record.getBean(Order.class);
            RecordQueryProConJunctionFactory rqpcjf = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.扣款记录_kkjl).getProConJunctionFactory()
                    .addEqual(DeductionHWANE16713Item.基本属性组_是否散户扣款, isRetail);
            rqpcjf.getRelationCriterionFactory(CarbonBaseConstant.订单记录_ddjl)
                    .setInRelationTypes(CarbonRelationType.RR_扣款记录_订单名称_订单记录)
                    .setInGuestCodes(order.getRecordCode());
            List<Deduction> kkList = rqpcjf.goBack().queryBeans(Deduction.class, 4);

            if (kkList != null) {
                for (Deduction deduction : kkList) {
                    // 税率判断
                    if (rate.compareTo(Optional.ofNullable(deduction.getTaxRate()).orElse(BigDecimal.ZERO)) < 0) {
                        rate = Optional.ofNullable(deduction.getTaxRate()).orElse(BigDecimal.ZERO);
                    }
                    if (deduction.getRecharge() == null
                            || deduction.getRecharge().getUnivalence() == null
                            || deduction.getRecharge().getUnivalence().getGoods() == null) {
                        log.info("数据异常，无充值等信息,{}", JSON.toJSON(deduction));
                        PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_14);
                        return;
                    }
//                    PrintInvoiceSet.InvoiceItemsSet item = new PrintInvoiceSet.InvoiceItemsSet();
//                    item.setItemId(order.getOrder());//订单编号
//                    item.setQuantity(deduction.getWeight() + "t");//数量
//                    item.setDiscountNet("0.00$");//折扣
//                    item.setDescription("");
//                    item.setBl(deduction.getRecharge().getOrder());
                    BigDecimal taxRate = new BigDecimal(String.valueOf(deduction.getRecharge().getUnivalence().getTaxRate())).divide(new BigDecimal("100"));
                    BigDecimal taxRateAdd1 = new BigDecimal("1").add(taxRate);
                    // 扣除税后单价
                    BigDecimal price = PublicMethod.divideBigDecimal(deduction.getRecharge().getUnivalence().getUnit(), taxRateAdd1, PublicConstant.leastUSD, null);
//                    item.setPrice(price.toPlainString() + "$");//单价
                    // 扣除税扣实际扣款金额（USD）
                    BigDecimal amount = PublicMethod.divideBigDecimal(deduction.getDeductionAmount(), taxRateAdd1, PublicConstant.leastUSD, null);
//                    item.setAmount(amount + "$");
                    // 扣除税扣实际扣款金额（CDF）
                    BigDecimal amountR = new BigDecimal(String.valueOf(deduction.getDeductionAmount()));
                    BigDecimal amountCDFR = PublicMethod.multiplyBigDecimal(amountR, deduction.getRecharge().getExchange(), PublicConstant.leastCDF, null);

                    totalAmountEXVAT = totalAmountEXVAT.add(amount);
                    avtAmount = avtAmount.add(amountR.subtract(amount));
                    amountUSD = amountUSD.add(amountR);
                    amountCDF = amountCDF.add(amountCDFR);
//					items.add(item);

                    //新增汇总
                    sumWeight = sumWeight.add(new BigDecimal(String.valueOf(deduction.getWeight())));

                    // 数据汇总
                    unitPriceMap.compute(price, (k, v) -> {
                        if (v == null) {
                            return new PublicEntity.NumberMoney(new BigDecimal(String.valueOf(deduction.getWeight())), amount);
                        } else {
                            v.setNumber(v.getNumber().add(new BigDecimal(String.valueOf(deduction.getWeight()))));
                            v.setMoney(v.getMoney().add(amount));
                            return v;
                        }
                    });
                    log.info("【开票】{}-{}扣款费用统计，扣款重量：{}，税前单价：{}，税前扣款金额：{}税后单价：{}，税后扣款金额：{}",
                            order.getOrder(), deduction.getRecordCode(), deduction.getWeight(), deduction.getUnit(), deduction.getDeductionAmount(), price, amount);
                }
            }
        }

        printInvoice.setRate(rate.toPlainString());

        //新增汇总
        String name = null;
        String code = null;
        StringBuffer number = new StringBuffer();
        StringBuffer money = new StringBuffer();
        StringBuffer unit = new StringBuffer();
        for (Map.Entry<BigDecimal, PublicEntity.NumberMoney> map : unitPriceMap.entrySet()) {
            PrintInvoiceSet.InvoiceItemsSet item = new PrintInvoiceSet.InvoiceItemsSet();
            Goods goods = PublicMethod.getInfo(CarbonBaseConstant.产品管理_cpgl, goodId, Goods.class, 2);
            name = goods.getName();
            if (goods.getMaterialAll() != null) {
                code = goods.getMaterialAll().getItemNum();
            }
            item.setDescription(name);
            item.setCode(code);
            if (String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())) {
                String value = configHWANE16627BNB.getConfigValueOneWeight();
                item.setQuantity(PublicMethod.divideBigDecimal(map.getValue().getNumber(), value, 0, RoundingMode.DOWN).toPlainString() + " Sac");
                BigDecimal unitPricePerBag = new BigDecimal(map.getKey().toPlainString().replace("$", "")).divide(new BigDecimal("20"), PublicConstant.leastUSD, RoundingMode.UP);
                item.setPrice(unitPricePerBag.toPlainString());
            } else {
                item.setQuantity(map.getValue().getNumber().toPlainString() + " tonne");
                item.setPrice(map.getKey().toPlainString());
            }
            item.setAmount(NumberUtil.decimalFormat(",###.##", map.getValue().getMoney()));

            number.append(item.getQuantity()).append(";");
            money.append(item.getAmount()).append(";");
            unit.append(map.getKey()).append(";");

            items.add(item);
        }

//		PrintInvoiceSet.InvoiceItemsSet item=new PrintInvoiceSet.InvoiceItemsSet();
//		Goods goods =PublicMethod.getInfo(CarbonBaseConstant.产品管理_cpgl, goodId,Goods.class,2);
//		item.setDescription(goods.getName());
//		if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType())){
//			String value=configHWANE16627BNB.getConfigValueOneWeight();
//			item.setQuantity(PublicMethod.divideBigDecimal(sumWeight,value,0, RoundingMode.DOWN).toPlainString());
//		}else {
//			item.setQuantity(sumWeight.toPlainString());
//		}
//		item.setAmount(totalAmountEXVAT.toPlainString());
//		items.add(item);

        printInvoice.setTotalAmountEXVAT(totalAmountEXVAT.toPlainString());//合计不含增值税
        printInvoice.setAvtAmount(avtAmount.toPlainString());//增值税进项税额
        printInvoice.setAmountUSD(amountUSD.toPlainString());//总金额美元
        printInvoice.setAmountCDF(amountCDF.toPlainString());//总金额人民币
        printInvoice.setItems(items);
        printInvoice.setSalesSlip(PublicMethod.getDateToString(Optional.ofNullable(info.getStartDate()).orElse(LocalDate.now()), PublicEnum.DateString.date4.getCode(), Locale.ENGLISH));
        printInvoice.setDate(PublicMethod.getDateToString(Optional.ofNullable(info.getEndDate()).orElse(LocalDate.now()), PublicEnum.DateString.date4.getCode(), Locale.ENGLISH));
        byte[] bytes = invoiceExportSetService.generatePdf(printInvoice, inputStream);
        if (bytes != null) {
            improveResultFactory.getProRecordOpsBuilder(CarbonBaseConstant.文件_wj)
                    .addRelation(CarbonRelationType.RR_文件_属于开票记录_开票记录, proRecord.getRecordCode())
                    .putFileAttribute(FileHWANE18503Item.基本属性组_文件, "factures.pdf", bytes, PublicEnum.FileType.pdf.getCode(), null);

            log.info("修改订单开票状态为true");
            for (ProRecord record : list) {
                improveResultFactory.getProRecordOpsBuilder(CarbonBaseConstant.订单记录_ddjl, record.getRecordCode())
                        .putAttribute(OrderHWANE16677Item.基本属性组_是否已开票, true);
            }
        } else {
            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_11);
            log.info("文件生成异常");
        }
        PublicMethod.saveAddNow(improveResultFactory)
                .putAttribute(InvoicingHWANE18525Item.基本属性组_Cash, isCash)
                .putAttribute(InvoicingHWANE18525Item.基本属性组_Credit, isCredit)
                .putAttribute(InvoicingHWANE18525Item.基本属性组_TotalAmountEXVAT, printInvoice.getTotalAmountEXVAT())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_VATAmount, printInvoice.getAvtAmount())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_TotalAmountInc_charge_USD_, printInvoice.getAmountUSD())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_TotalAmountInc_charge_CDF_, printInvoice.getAmountCDF())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_产品, name)
                .putAttribute(InvoicingHWANE18525Item.基本属性组_数量, number.toString())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_金额, money.toString())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_编号, code)
                .putAttribute(InvoicingHWANE18525Item.基本属性组_单价, unit.toString())
                .putAttribute(InvoicingHWANE18525Item.基本属性组_税率, rate.toPlainString())
        ;
    }

    private void saveInvoicingNewInput(ProRecord proRecord, Invoicing info, Customer customer, InvoiceInfo invoiceInfo, ImproveResultFactory improveResultFactory, InvoiceHeader invoiceHeader, byte[] inputStream) {
        log.info("开始生成发票,{}", proRecord.toJson());

        PrintInvoiceSet printInvoice = new PrintInvoiceSet();
        printInvoice.setClientName(customer.getName());

        printInvoice.setGckVATNO(invoiceHeader.getData1());
        printInvoice.setGckNIF(invoiceHeader.getData2());
        printInvoice.setGckIDN(invoiceHeader.getData3());
        printInvoice.setSalesSlip(PublicMethod.getDateToString(Optional.ofNullable(info.getStartDate()).orElse(LocalDate.now()), PublicEnum.DateString.date4.getCode(), Locale.ENGLISH));
        printInvoice.setDate(PublicMethod.getDateToString(Optional.ofNullable(info.getEndDate()).orElse(LocalDate.now()), PublicEnum.DateString.date4.getCode(), Locale.ENGLISH));

        printInvoice.setInvoiceNo(PublicMethod.getOrderCodeFV());//发票号
        printInvoice.setClientVATNO(invoiceInfo.getData1());
        printInvoice.setClientNIF(invoiceInfo.getData2());
        printInvoice.setClientVAT(invoiceInfo.getVat());
        printInvoice.setClientIDN(invoiceInfo.getData3());
        printInvoice.setAddress(invoiceInfo.getCountry());//地址信息
        printInvoice.setRemark(invoiceInfo.getProvinces());

        printInvoice.setCash(info.getCash());
        printInvoice.setCredit(info.getCredit());

        printInvoice.setTotalAmountEXVAT(info.getTotalAmountEXVAT());//合计不含增值税
        printInvoice.setAvtAmount(info.getVATAmount());//增值税进项税额
        printInvoice.setAmountUSD(info.getTotalAmountIncChargeUSD());//总金额美元
        printInvoice.setAmountCDF(info.getTotalAmountIncChargeCDF());//总金额人民币

        printInvoice.setRate(info.getRate().toPlainString());

        String[] quantity = info.getQuantity().split(";");
        String[] amount = info.getAmount().split(";");
        String[] unit = info.getUnit().split(";");
        List<PrintInvoiceSet.InvoiceItemsSet> items = new ArrayList<>();
        for (int i = 0; i < quantity.length; i++) {

            PrintInvoiceSet.InvoiceItemsSet item = new PrintInvoiceSet.InvoiceItemsSet();
            item.setDescription(info.getDescription());
            item.setQuantity(quantity[0]);
            item.setAmount(amount[0]);
            item.setPrice(unit[0]);
            item.setCode(info.getCode());
            items.add(item);
        }


        printInvoice.setItems(items);

        byte[] bytes = invoiceExportSetService.generatePdf(printInvoice, inputStream);
        if (bytes != null) {
            improveResultFactory.getProRecordOpsBuilder(CarbonBaseConstant.文件_wj)
                    .addRelation(CarbonRelationType.RR_文件_属于开票记录_开票记录, proRecord.getRecordCode())
                    .putFileAttribute(FileHWANE18503Item.基本属性组_文件, "factures.pdf", bytes, PublicEnum.FileType.pdf.getCode(), null);
        } else {
            PublicMethod.returnMessage(improveResultFactory, PublicReturn.INVOICING_11);
            log.info("文件生成异常");
        }
    }
}
